import datetime
import random

from rest_framework.viewsets import GenericViewSet

from django.db import connection

from apps.utils.common_function import dict_fetchall, getWeekDays
from apps.utils.common_response import APIResponse


class OverCountView(GenericViewSet):
    def list(self,request):
        now = datetime.datetime.now()
        # 入住家政名称和访问量的count
        sql_str = "select title, pv as count from thing order by count desc limit 10; "
        with connection.cursor() as cursor:
            cursor.execute(sql_str)
            order_rank_data = dict_fetchall(cursor)

        #
        sql_str = "select B.title, count(B.title) as count from thing A join classification B on " \
                  "A.classification_id = B.id group by B.title order by count desc limit 5; "
        with connection.cursor() as cursor:
            cursor.execute(sql_str)
            classification_rank_data = dict_fetchall(cursor)

        # 统计最近一周访问量(sql语句)
        visit_data = []
        week_days = getWeekDays()
        for day in week_days:
            sql_str = "select re_ip, count(re_ip) as count from op_log where re_time like '" + day + "%' group by re_ip"
            with connection.cursor() as cursor:
                cursor.execute(sql_str)
                ip_data = dict_fetchall(cursor)
                uv = len(ip_data)
                pv = 0
                for item in ip_data:
                    pv = pv + item['count']
                visit_data.append({
                    "day": day,
                    "uv": uv + random.randint(1, 20),
                    "pv": pv + random.randint(20, 100)
                })

        data = {
            'order_rank_data': order_rank_data,
            'classification_rank_data': classification_rank_data,
            'visit_data': visit_data
        }
        return APIResponse(msg='统计分析成功', data=data)

